
package com.budwk.app.sqfw.controllers.admin;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.component.PushMsgComponent;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.starter.common.constant.RedisConstant;
import com.budwk.starter.common.openapi.annotation.ApiDefinition;
import com.budwk.starter.common.openapi.annotation.ApiFormParam;
import com.budwk.starter.common.openapi.annotation.ApiFormParams;
import com.budwk.starter.common.openapi.annotation.ApiOperation;
import com.budwk.starter.log.annotation.SLog;
import com.huawei.push.android.*;
import com.huawei.push.exception.HuaweiMesssagingException;
import com.huawei.push.message.AndroidConfig;
import com.huawei.push.message.Message;
import com.huawei.push.message.Notification;
import com.huawei.push.messaging.HuaweiApp;
import com.huawei.push.messaging.HuaweiMessaging;
import com.huawei.push.model.Importance;
import com.huawei.push.model.Urgency;
import com.huawei.push.model.Visibility;
import com.huawei.push.reponse.SendResponse;
import com.huawei.push.util.InitAppUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;

import java.util.HashMap;
import java.util.Map;


/**
 * @title: SendNotifyMessageController
 * @Author Tan
 * @Date: 2023/7/21 9:46
 * @Version 1.0
 */
@IocBean
@At("/platform/sqfw/sendnotifymessage")
@ApiDefinition(tag = "消息推送")
@Slf4j
public class SendNotifyMessageController {

    @Inject
    private RedisService redisService;

    @Inject
    private SysUserService userService;


    @At("/sendhuaweinotifymessage")
    @Ok("json")
    @POST
    @ApiOperation(name = "发送华为通知")
    @ApiFormParams()
    @SLog(tag = "发送华为通知", value = "${args[0]}")
    public SendResponse sendhuaweinotifymessage(@Param("token") String token) throws HuaweiMesssagingException {
        HuaweiApp app = InitAppUtils.initializeApp();
        HuaweiMessaging huaweiMessaging = HuaweiMessaging.getInstance(app);

        Notification notification = Notification.builder().setTitle("祥云小助")
                .setBody("您有新的消息！")
                .build();

        JSONObject multiLangKey = new JSONObject();
        JSONObject titleKey = new JSONObject();
        titleKey.put("en","好友请求");
        JSONObject bodyKey = new JSONObject();
        bodyKey.put("en","My name is %s, I am from %s.");
        multiLangKey.put("key1", titleKey);
        multiLangKey.put("key2", bodyKey);

        LightSettings lightSettings = LightSettings.builder().setColor(Color.builder().setAlpha(0f).setRed(0f).setBlue(1f).setGreen(1f).build())
                .setLightOnDuration("3.5")
                .setLightOffDuration("5S")
                .build();

        BadgeNotification badgeNotification= BadgeNotification.builder()
                .setAddNum(1)
                .build();

        AndroidNotification androidNotification = AndroidNotification.builder().setIcon("/raw/ic_launcher2")
                .setColor("#AACCDD")
                .setSound("/raw/shake")
                .setDefaultSound(true)
                .setTag("tagBoom")
                .setClickAction(ClickAction.builder().setType(1).setIntent("https://www.huawei.com").build())
                .setBodyLocKey("key2")
                .addBodyLocArgs("boy").addBodyLocArgs("dog")
                .setTitleLocKey("key1")
                .addTitleLocArgs("Girl").addTitleLocArgs("Cat")
                .setChannelId("NotificationChannelImportantId")
/*
                .setNotifySummary("some summary")
*/
                .setMultiLangkey(multiLangKey)
                .setStyle(0)
                .setBigTitle("祥云小助")
                //消息内容
                .setBigBody("Big Boom Body")
                .setAutoClear(86400000)
                .setNotifyId(486)
                //.setGroup("com.dfsjsoft.communityassistant.GROUP_KEY_MESSAGE_RECEIVED")
                .setImportance(Importance.NORMAL.getValue())
                .setLightSettings(lightSettings)
                .setBadge(BadgeNotification.builder().setAddNum(1).setBadgeClass("com.dfsjsoft.communityassistant.ui.main.MainActivity").build())
                .setVisibility(Visibility.PUBLIC.getValue())
                .setForegroundShow(true)
                .addInboxContent("content1").addInboxContent("content2").addInboxContent("content3").addInboxContent("content4").addInboxContent("content5")
                /*.addButton(Button.builder().setName("button1").setActionType(0).build())
                .addButton(Button.builder().setName("button2").setActionType(1).setIntentType(0).setIntent("https://com.huawei.hms.hmsdemo/deeplink").build())
                .addButton(Button.builder().setName("button3").setActionType(4).setData("your share link").build())*/
                .build();

        AndroidConfig androidConfig = AndroidConfig.builder().setCollapseKey(-1)
                .setUrgency(Urgency.HIGH.getValue())
                .setTtl("10000s")
                .setBiTag("the_sample_bi_tag_for_receipt_service")
                .setNotification(androidNotification)
                .setCategory("WORK")
                .build();

        Message message = Message.builder().setNotification(notification)
                .setAndroidConfig(androidConfig)
                .addToken(token)
                .build();


        SendResponse response = huaweiMessaging.sendMessage(message);

        return response;
    }


    /**
     *
     * @param pushToken 推送token
     * @param phone 登陆人手机号
     * @param pushChannel 推送渠道
     * @return
     */
    @At("/setToken")
    @Ok("json")
    @POST
    @ApiOperation(name = "保存token到redis")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "pushToken", description = "主键", required = true, check = true,example = "IQAAAACy01jQAABxEYvAESSjp2H0eWSE7i6TOFJ9GNVPcKfjdRckjTqhzpF8I71r_GZX2LWVh2w0XlBbpaFsPqVqCqhf2kTt3Fw-8ditTX5VsqjR_Q"),
                    @ApiFormParam(name = "phone", description = "启用禁用", required = true, check = true, example = "17585379278", type = "boolean"),
                    @ApiFormParam(name = "pushChannel", description = "启用禁用", required = true, check = true, example = "华为", type = "boolean")

            }
    )
    @SLog(tag = "保存token到redis", value = "${args[0]},${args[1]},${args[2]}")
    public String setToken(@Param("pushToken") String pushToken,@Param("phone") String phone,@Param("pushChannel") String pushChannel){
        log.info("-----------------setToken phone param*********: {}", phone);
        String getToken=redisService.get(phone);
        String result="";
        String pushUserJson="";
        if (Strings.isNotBlank(getToken)||getToken!=null){
            Map<String, String> map = new HashMap<>();
            String[] keyValuePairs = getToken.split(";");
            for (String pair : keyValuePairs) {
                String[] entry = pair.split("=");
                map.put(entry[0], entry[1]);
            }
            map.replace("pushToken",pushToken);
            map.replace("pushChannel",pushChannel);

            result=map.toString();
            pushUserJson = JSONObject.toJSONString(map);
        }else {
            Map map=new HashMap();
            map.put("pushToken",pushToken);
            map.put("pushChannel",pushChannel);
            result=redisService.hmset(RedisConstant.PRE + "push:token:" + phone,map);
            pushUserJson = JSONObject.toJSONString(map);
        }
        if (StringUtils.isNotEmpty(phone)) {
            Sys_user user = userService.getUserByLoginname(phone);
            if (user != null) {
                if (StringUtils.isEmpty(user.getPushMobileInfo()) || !pushUserJson.equals(user.getPushMobileInfo())) {
                    user.setPushMobileInfo(pushUserJson);
                    userService.updateIgnoreNull(user);
                }
            }
        }
        return  result;
    }



    @At("/getToken")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取token")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "phone", description = "启用禁用", required = true, check = true, example = "17585379278", type = "boolean"),
            }
    )
    @SLog(tag = "获取token", value = "${args[0]}")
    public String getToken(@Param("phone") String phone){
        Map getToken=redisService.hgetAll(RedisConstant.PRE + "push:token:" +phone);
        String result="";
            result=getToken.toString();
        return  result;
    }
}


